package com.itheima.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ImageServiceImpl {
	@Autowired
	private RedisTemplate redisTemplate;
	@Value("${health.alioss.endpoint}")
	private String endpoint;

	@Value("${health.alioss.access-key-id}")
	private String accessKeyId;

	@Value("${health.alioss.access-key-secret}")
	private String accessKeySecret;

	@Value("${health.alioss.bucket-name}")
	private String bucketName;

	// 保存上传的图片名称到Redis集合
	public void saveUploadedImages(String imageNames) {

		redisTemplate.opsForSet().add("uploadedImages", imageNames);
	}

	// 保存套餐数据中的图片名称到Redis集合
	public void savePackageImages(String imageNames) {
		redisTemplate.opsForSet().add("packageImages", imageNames);
	}

	// 计算垃圾图片名称
	private Set<String> getGarbageImages() {
		Set<String> uploadedImages = redisTemplate.opsForSet().members("uploadedImages");
		Set<String> packageImages = redisTemplate.opsForSet().members("packageImages");
		// 过滤掉套餐数据中的图片名称
		return uploadedImages.stream()
				.filter(image -> !packageImages.contains(image))
				.collect(Collectors.toSet());
	}

	// 删除阿里云OSS中的垃圾图片
	private void deleteGarbageImages() {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		Set<String> garbageImages = getGarbageImages();

		garbageImages.forEach(imageName -> {
			try {
				ossClient.deleteObject(bucketName, imageName);
				System.out.println("Deleted garbage image: " + imageName);
				redisTemplate.opsForSet().remove("uploadedImages", imageName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

		ossClient.shutdown();
	}

	//删除redis及OSS中的图片路径数据
	public void deleteImage(String imageName) {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		ossClient.deleteObject(bucketName, imageName);
		redisTemplate.opsForSet().remove("packageImages", imageName);
		redisTemplate.opsForSet().remove("uploadedImages", imageName);
	}

	// 定时任务，定时计算并删除垃圾图片
	@Scheduled(fixedRate = 3600000) // 每小时执行一次
	public void scheduledDeleteGarbageImages() {
		deleteGarbageImages();
	}
}
